package com.lej.push.provider

import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.Postcard
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import com.lej.core.base.AppManager
import com.lej.core.base.homeActivity
import com.lej.core.common.userIsLogin
import com.lej.core.provider.PushProvider
import com.lej.core.provider.unityProvider
import com.lej.core.router.CRouter
import com.lej.core.utils.KLog
import com.lej.core.utils.extention.addClearFlag
import com.lej.core.utils.extention.fromJson
import com.lej.core.utils.extention.logI
import com.lej.core.utils.extention.router
import java.net.URLDecoder
import java.nio.charset.StandardCharsets

/*
 *intent://com.lej.club/deeplink?#Intent;scheme=push_scheme;launchFlags=0x4000000;package=com.lej.club;component=com.lej.club/com.lej.push.DeeplinkActivity;S.name=sss;i.age=18;end
 */

object PushProviderImpl : PushProvider {
    override suspend fun pushMap(act: AppCompatActivity) {
        val tmpIntent = cacheIntent ?: return
        if (!userIsLogin()) {//尚未登录,进入登录页面
            act.router(CRouter.login) { addClearFlag() }
            return
        }
        if (!AppManager.hasTagActivity(homeActivity?.simpleName)) {//未打开首页,先进入首页
            act.router(CRouter.newMain) { addClearFlag() }
            return
        }
        runCatching {
            val key = tmpIntent.getIntExtra(KEY_TYPE, -1)
            val data = tmpIntent.getStringExtra(KEY_DATA)
            when (key) {
                MSG_CENTER -> act.router(CRouter.newmy)
                NFT_DETAIL -> {}
                PROTOCOL_ROUTER -> {
                    val jsonObject = data?.fromJson<JsonObject>() ?: return
                    act.router(jsonObject.get(KEY_ROUTE).asString) {
                        jsonObject.keySet().forEach { putData(it, jsonObject.get(it)) }
                    }
                }
                TO_HOME -> {}
                ENTER_SPACE -> {//进入空间
                    val jo = data?.urlDecoder()?.fromJson<JsonObject>() ?: return
                    val houseId = jo.get(KEY_HOUSE_ID).asInt
                    unityProvider?.enter3DRoom(act, houseId, act.isHomeAct())
                }
                DEFAULT_PROTOCOL-> {
                    data?.protocolData()
                }
                else -> {}
            }
            tmpIntent.extras?.toString()?.logI("sss")
        }
        cacheIntent = null
    }

    private fun AppCompatActivity.isHomeAct(): Boolean {
        return this.javaClass.simpleName == homeActivity?.simpleName
    }

    private fun String.protocolData() {
        val uri = Uri.parse(this)
        val scheme = uri.scheme
        val host = uri.host
        val path = uri.path
        KLog.e("scheme:${scheme}---host:${host}---path${path}")
    }

    private const val KEY_TYPE = "type"
    private const val KEY_DATA = "data"
    private const val KEY_ROUTE = "route"
    private const val KEY_HOUSE_ID = "houseId"

    private const val DEFAULT_PROTOCOL = -1//默认返回值,通过协议解析
    private const val MSG_CENTER = 1//消息中心
    private const val NFT_DETAIL = 2//nft详情
    private const val TO_HOME = 100//进入首页
    private const val ENTER_SPACE = 101//进入空间
    private const val PROTOCOL_ROUTER = 888//通用协议中转路由

    var cacheIntent: Intent? = null

    private fun Postcard.putData(key: String, je: JsonElement?) {
        if (KEY_ROUTE == key) return
        (je as? JsonPrimitive)?.apply {
            when {
                isBoolean -> withBoolean(key, asBoolean)
                isString -> withString(key, asString)
                isNumber -> asNumber.let {
                    when (it) {
                        is Int -> withInt(key, it)
                        is Long -> withLong(key, it)
                        is Double -> withDouble(key, it)
                        is Short -> withShort(key, it)
                        is Float -> withFloat(key, it)
                        else -> {}
                    }
                }
            }
        }
    }


    private fun String.urlDecoder() =
        runCatching { URLDecoder.decode(this, StandardCharsets.UTF_8.name()) }.getOrNull()
}